package io.renren.common.utils;

import java.io.IOException;
import java.util.concurrent.*;

public class ThreadTest {
    static ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 15, 5, TimeUnit.MINUTES,
            new LinkedBlockingQueue<>(20));

    public static void main(String[] args) throws InterruptedException, IOException {

        executor.prestartAllCoreThreads(); // 预启动所有核心线程

        for (int i = 1; i <= 100; i++) {
            while (!exe(String.valueOf(i))) {
                Thread.sleep(3000);// 让主线程睡眠三秒
            }
        }
        executor.shutdown();// 关闭线程池
//        System.in.read(); //阻塞主线程
    }

    static boolean exe(String i) {
        try {
            MyTask task = new MyTask(String.valueOf(i));
            executor.execute(task);
            return true;
        } catch (RejectedExecutionException e) {
            return false;
        }
    }


    static class MyTask implements Runnable {
        private String name;

        public MyTask(String name) {
            this.name = name;
            System.out.println(this.toString() + "new ");
        }

        @Override
        public void run() {
            try {
                System.out.println(this.toString() + " is running start!");
                Thread.sleep(3000); //让任务执行慢点
                System.out.println(this.toString() + " is running end!");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        public String getName() {
            return name;
        }

        @Override
        public String toString() {
            return "MyTask [name=" + name + "]";
        }
    }
}
